package com.levy.utils;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 郭利伟 on 2017.08.10.
 */
public class HttpUtil1 {
    public static String sendHttpRequest(
            String urlstr,String method,String outputstr,String charset) throws Throwable{
        URL url=new URL(urlstr);
        HttpURLConnection conn=(HttpURLConnection)
                url.openConnection();
        conn.setDoInput(true);
        if(outputstr!=null){
            conn.setDoOutput(true);
        }
        conn.setUseCaches(false);
        conn.setConnectTimeout(1000*60);
        conn.setReadTimeout(1000*60);
        conn.setRequestMethod(method);

        if(outputstr!=null){
            OutputStream output=conn.getOutputStream();

            PrintWriter writer=new PrintWriter(new
                    OutputStreamWriter(output,charset));
            writer.write(outputstr);
            writer.flush();
            writer.close();

        }

        InputStream input=conn.getInputStream();
        BufferedReader reader=new BufferedReader(
                new InputStreamReader(input,charset)
        );
        StringBuilder strbuf=new StringBuilder();
        String line=null;
        while((line=reader.readLine())!=null){
            strbuf.append(line);
        }
        input.close();
        conn.disconnect();
        return strbuf.toString();
    }

    /**
     * get方法直接调用post方法
     * @param url 网络地址
     * @param  charSet 编码
     * @return 返回网络数据
     */
    public static String get(String url,String charSet){
        return post(url,charSet,null);
    }
    /**
     * 设定post方法获取网络资源,如果参数为null,实际上设定为get方法
     * @param url 网络地址
     * @param  charSet 编码
     * @param param 请求参数键值对
     * @return 返回读取数据
     */
    public static String post(String url,String charSet,Map<String,String> param){
        HttpURLConnection conn=null;
        try {
            URL u=new URL(url);
            conn=(HttpURLConnection) u.openConnection();
            StringBuffer sb=null;
            if(param!=null){//如果请求参数不为空
                sb=new StringBuffer();
                /*A URL connection can be used for input and/or output. Set the DoOutput
                 * flag to true if you intend to use the URL connection for output,
                 * false if not. The default is false.
                 * httpUrlConnection.setDoOutput(true);以后就可以使用conn.getOutputStream().write()
                   httpUrlConnection.setDoInput(true);以后就可以使用conn.getInputStream().read();
                */
                //默认为false,post方法需要写入参数,设定true
                conn.setDoOutput(true);
                //设定post方法,默认get
                conn.setRequestMethod("POST");
                //获得输出流
                OutputStream out=conn.getOutputStream();
                //对输出流封装成高级输出流
                BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(out,charSet));
                //将参数封装成键值对的形式
                for(Map.Entry s:param.entrySet()){
                    sb.append(s.getKey()).append("=").append(s.getValue()).append("&");
                }
                //将参数通过输出流写入
                writer.write(sb.deleteCharAt(sb.toString().length()-1).toString());
                writer.close();//一定要关闭,不然可能出现参数不全的错误
                sb=null;
            }
            conn.connect();//建立连接
            sb=new StringBuffer();
            //获取连接状态码
            int recode=conn.getResponseCode();
            BufferedReader reader=null;
            if(recode==200){
                //Returns an input stream that reads from this open connection
                //从连接中获取输入流
                InputStream in=conn.getInputStream();
                //对输入流进行封装
                reader=new BufferedReader(new InputStreamReader(in,charSet));
                String str=null;
                sb=new StringBuffer();
                //从输入流中读取数据
                while((str=reader.readLine())!=null){
                    sb.append(str).append(System.getProperty("line.separator"));
                }
                //关闭输入流
                reader.close();
                if (sb.toString().length() == 0) {
                    return null;
                }
                return sb.toString().substring(0,
                        sb.toString().length() - System.getProperty("line.separator").length());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally{
            if(conn!=null)//关闭连接
                conn.disconnect();
        }
        return null;
    }


    public static void main(String[] args) {
        String url = "http://u6.gg/gPWu3";
//        String s = HttpUtil.get("https://www.2345.com/?kguoliwei","gbk");
//        Map m = new HashMap();
//        m.put("tel","13800138000");
//        m.put("sex","f");
//        String s = HttpUtil1.post("https://tcc.taobao.com/cc/json/mobile_tel_segment.htm","gbk",m);
//        System.out.println(s);
        String s = get(url, "utf-8");
        System.out.println(s);

    }

}
